#include "dda.h"
#include <QDebug>
#include <QPoint>

DDA::DDA()
{
    mFirstPoint = 0;
    mPoints = new QList<QPoint>;
}

PointsIter* DDA::handleMoveEvent(QPoint point){
    if (mFirstPoint)
        return calculate(point);
    return 0;
}

bool DDA::isTemp(){
    return mFirstPoint;
}

void DDA::drop(){
    if (mFirstPoint)
        delete mFirstPoint;
    mFirstPoint = 0;
}

PointsIter* DDA::handlePressEvent(QPoint point){
    if (!mFirstPoint){
        mFirstPoint = new QPoint(point.x(), point.y());
        mPoints->clear();
        mPoints->append(*mFirstPoint);
        return new PointsIter(*mPoints);
    }
    else{
        PointsIter* res = calculate(point);
        mFirstPoint = 0;
        return res;
    }
}

PointsIter* DDA::calculate(QPoint point){

    mPoints->clear();
    if ((*mFirstPoint) == point){
        mPoints->append(*mFirstPoint);
        return new PointsIter(*mPoints);
    }
    QPoint delta = point - *mFirstPoint;
    int lenght = qMax(qAbs(delta.x()), qAbs(delta.y()));
    double dx = double(delta.x()) / lenght;
    double dy = double(delta.y()) / lenght;
    double x = mFirstPoint->x();
    double y = mFirstPoint->y();
    mPoints->append(*mFirstPoint);
    for(int i=1; i < lenght; i++){
        x += dx;
        y += dy;
        mPoints->append(QPoint(qRound(x), qRound(y)));
    }
    mPoints->append(point);
    if (!mPoints->length())
        return 0;
    return new PointsIter(*mPoints);
}
